const { Router } = require("express");
const express = require("express");
const addgoods = require("../model/Addgoods");
const multer = require("multer");
const path = require("path");
const router = new Router();

router.use("/upload", express.static(path.join(__dirname, "static/upload")));
// 获取图片路径及其他数据后添加商品数据
// http://localhost:8000/api/addgoods/add
router.post("/add", async (req, res) => {
  // if (!req.file) {
  //   return res.status(400).json({ message: "未上传文件" });
  // }
  // let file = req.file;
  try {
    const {
      title,
      description,
      category,
      variety,
      specifications,
      storageCondition,
      currentPrice,
      originalPrice,
      recommended,
      recommendationReason,
      photos,
      flashSale,
      snappingPrice,
      preferential,
      preferentialPrice,
    } = req.body;
    const flashSaleBool = Boolean(flashSale);
    const preferentialBool = Boolean(preferential);
    await addgoods.create({
      title,
      description,
      category,
      variety,
      specifications,
      storageCondition,
      currentPrice,
      originalPrice,
      recommended,
      recommendationReason,
      photos,
      flashSale: flashSaleBool,
      snappingPrice,
      preferential: preferentialBool,
      preferentialPrice,
    });
    res.status(200).json({ message: "添加成功" });
  } catch (error) {
    console.log(error);
    res.status(400).json({ message: "服务端错误", error });
  }
});
router.get("/all", async (req, res) => {
  addgoods
    .find()
    .then((addgoodsList) => {
      res.json(addgoodsList);
    })
    .catch((err) => {
      console.log(err);
      res.status(500).json({ error: "后端错误" });
    });
});

//根据商品id查询
router.post("/findone", async (req, res) => {
  let { id } = req.body;
  let result = await addgoods.findById({ _id: id });
  res.status(200).json({ mag: "查询成功", data: result });
});
//获取所有商品的数据 http://localhost:8000/api/addgoods/getAll
router.get("/getAll", async (req, res) => {
  try {
    const data = await addgoods.find();
    res.send({
      code: 200,
      status: true,
      msg: data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 400,
      status: false,
      msg: "请求出错",
    });
  }
});

//通过id值获取对应的商品 http://localhost:8000/api/addgoods/getProduct
// router.post()

module.exports = router;
